<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>基本信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name" :rules="[{ required: true, message: '编码名称为必填项', trigger: 'blur' }]">
								<template #label>
									<WtmLabelTooltip label="编码名称" tooltip="编码规则的名称" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Name" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_CodeType_FormItem"
								prop="Entity.CodeType"
								:rules="[{ required: true, message: '编码类型为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="编码类型" tooltip="业务单据类型（使用模型名称）" />
								</template>
								<el-cascader
									:options="stateData.allBillList"
									:props="{ checkStrictly: false, emitPath: false, label: 'Text', value: 'Value', children: 'Children' }"
									clearable
									filterable
									class="w100"
									v-model="stateData.vmModel.Entity.CodeType"
									@change="onCodeTypeChange"
								/>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>编码规则</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Prefix_FormItem" prop="Entity.Prefix">
								<template #label>
									<WtmLabelTooltip label="编码前缀" tooltip="编码的固定前缀" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Prefix" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_DateFormat_FormItem" prop="Entity.DateFormat">
								<template #label>
									<WtmLabelTooltip label="日期格式" tooltip="编码中的日期格式，如：yyyyMMdd、yyyyMM等" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.DateFormat" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_SerialLength_FormItem"
								prop="Entity.SerialLength"
								:rules="[{ required: true, message: '序号长度为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="序号长度" tooltip="序号部分的位数" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.SerialLength" clearable class="width100"></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Suffix_FormItem" prop="Entity.Suffix">
								<template #label>
									<WtmLabelTooltip label="编码后缀" tooltip="编码的固定后缀" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Suffix" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_ResetRule_FormItem"
								prop="Entity.ResetRule"
								:rules="[{ required: true, message: '重置规则为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="重置规则" tooltip="序号重置规则" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.ResetRule" clearable class="width100">
									<el-option key="Never" value="Never" label="永不重置"></el-option>
									<el-option key="Daily" value="Daily" label="每日重置"></el-option>
									<el-option key="Monthly" value="Monthly" label="每月重置"></el-option>
									<el-option key="Yearly" value="Yearly" label="每年重置"></el-option
								></el-select>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>状态信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_CurrentSerial_FormItem"
								prop="Entity.CurrentSerial"
								:rules="[{ required: true, message: '当前序号为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="当前序号" tooltip="当前的序号值" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.CurrentSerial" clearable class="width100"></el-input-number>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_IsEnabled_FormItem"
								prop="Entity.IsEnabled"
								:rules="[{ required: true, message: '是否启用为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="是否启用" tooltip="是否启用此编码规则" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.IsEnabled" clearable class="width100">
									<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
									<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Sort_FormItem" prop="Entity.Sort" :rules="[{ required: true, message: '排序为必填项', trigger: 'blur' }]">
								<template #label>
									<WtmLabelTooltip label="排序" tooltip="显示排序" />
								</template>
								<el-input-number v-model="stateData.vmModel.Entity.Sort" clearable class="width100"></el-input-number>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>其他</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
								<template #label>
									<WtmLabelTooltip label="备注" tooltip="备注信息" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Remark" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div style="text-align: right">
					<WtmButton @click="onSave" type="primary" :button-text="$t('message._system.common.vm.submit')" style="margin-top: 15px" />

					<WtmButton @click="onClose" type="default" :button-text="$t('message._system.common.vm.cancel')" style="margin-top: 15px" />
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.add;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed } from 'vue';
import { SysCodeRuleApi as api } from '/@/views/_admin/syscoderule/api';
import other from '/@/utils/other';
import { ISysCodeRuleVm } from '/@/views/_admin/syscoderule/api/interface';
import { IViewModel } from '/@/types/common';

const ci = getCurrentInstance() as any;
const loading = ref(false);
// 定义变量内容
const formRef = ref();
const stateData = reactive<IViewModel<ISysCodeRuleVm>>({
	vmModel: {
		Entity: {
			Name: null,
			CodeType: null,
			Prefix: null,
			DateFormat: 'yyyyMMdd',
			SerialLength: 4,
			Suffix: null,
			ResetRule: null,
			CurrentSerial: 0,
			LastGenerateTime: null,
			LastResetTime: null,
			IsEnabled: false,
			Sort: 0,
			Remark: null,
			TenantCode: null,
		},
	},
	allBillList: [],
});

// 取消
const onClose = () => {
	closeDialog();
};

// 编码类型改变时的处理
const onCodeTypeChange = (value: string) => {
	if (value) {
		// 在所有选项中查找选中的项
		const findItemByValue = (items: any[], targetValue: string): any => {
			for (const item of items) {
				if (item.Value === targetValue) {
					return item;
				}
				if (item.Children && item.Children.length > 0) {
					const found = findItemByValue(item.Children, targetValue);
					if (found) return found;
				}
			}
			return null;
		};

		const selectedItem = findItemByValue(stateData.allBillList, value);
		if (selectedItem && selectedItem.Tag) {
			stateData.vmModel.Entity.Name = selectedItem.Tag;
		}
	}
};

// 提交
const onSave = () => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			api()
				.add(stateData.vmModel)
				.then(() => {
					ElMessage.success(ci.proxy.$t('message._system.common.vm.submittip'));
					emit('refresh');
					closeDialog();
				})
				.catch((error) => {
					other.setFormError(ci, error);
				})
				.finally(() => {
					loading.value = false;
				});
		}
	});
};

// 页面加载时
onMounted(() => {
	loading.value = true;
	if (ci.attrs['wtmdata']) {
		stateData.vmModel.Entity.ID = ci.attrs['wtmdata'].ID;
	}
	const promises: Promise<any>[] = [
		other.getSelectList('/api/SysCodeRule/GetBillList', [], false).then((x) => {
			stateData.allBillList = x;
		}),
	];
	Promise.allSettled(promises).finally(() => {
		loading.value = false;
	});
});

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh', 'closeDialog']);
// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};
</script>
